package com.cms.kernel.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Copyright (C) 2013 2016 Well
 * 文件:ResponseUtil.java
 * 创建:Well
 * 日期:2016年5月25日 下午3:09:46
 * 来自:
 * 版本:1.0.0
 * 描述:响应的util类，将后台处理的结果响应到前台
 */

public class ResponseUtil
{
    private static Logger logger= LogManager.getLogger(ResponseUtil.class);

    /**
     * 发送文本内容
     * @param response 响应
     * @param content 文本内容
     */
    public static void renderText(HttpServletResponse response,String content)
    {
        render(response, "text/plain;charset=UTF-8", content);
    }

    /**
     * 发送html内容
     * @param response 响应
     * @param content html内容
     */
    public static void renderHTML(HttpServletResponse response,String content)
    {
    	render(response,"text/html;charset=UTF-8",content);
    }
    
    /**
     * 发送json内容
     * @param response 响应
     * @param content json格式的内容
     */
    public static void renderJSON(HttpServletResponse response, String content)
    {
        render(response, "application/json;charset=UTF-8", content);
    }

    /**
     * 发送xml内容
     * @param response 响应
     * @param content XML格式的内容
     */
    public static void renderXML(HttpServletResponse response, String content)
    {
        render(response, "text/xml;charset=UTF-8", content);
    }

    /**
     * 发送指定contentType类型的内容到前台
     * @param response 响应
     * @param contentType 类型
     * @param content 内容
     */
    public static void render(HttpServletResponse response,String contentType,String content)
    {
        PrintWriter writer=null;

        try
        {
            setProperty(response, contentType);
            
            writer=response.getWriter();
            writer.write(content);
        }
        catch (IOException e)
        {
            logger.error(e);
        }
        finally
        {
        	if(null!=writer)
        	{
        		writer.flush();
                writer.close();
        	}
        }
    }
    
    /**
     * 设置响应的属性
     * @param response
     * @param contentType
     */
    private static void setProperty(HttpServletResponse response,String contentType)
    {
    	response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
    }

}
